<template>
    <div>
        <el-dialog
                v-dialogDrag :visible.sync="chartDivDialogVisible.v"
                width="65%"
                title="添加图表">
            <div class="content" v-loading="isLoad">
                <el-col :span="8">
                    <div>
                        <p>选择数据：</p>
                        <el-select style="width:90%;"
                                   v-model="value" clearable placeholder="请选择添加数据"
                                   @change="changeDataFields">
                            <el-option
                                    v-for="item in myOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div>
                        <p style="margin-top: 20px">选择X轴：</p>
                        <el-select style="width:90%;"
                                   v-model="xfield" clearable :disabled="this.isSelected" placeholder="请选择X轴">
                            <el-option
                                    v-for="item in fieldOption"
                                    :key="item.xfield"
                                    :label="item.xfieldName"
                                    :value="item.xfield">
                            </el-option>
                        </el-select>
                    </div>
                    <div>
                        <p style="margin-top: 20px">选择Y轴：</p>
                        <el-select style="width:90%;"
                                   v-model="yfield" clearable :disabled="this.isSelected" placeholder="请选择Y轴">
                            <el-option
                                    v-for="item in fieldOptions"
                                    :key="item.yfield"
                                    :label="item.yfieldName"
                                    :value="item.yfield">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="block">
                        <p style="margin-top: 20px">时间范围：</p>
                        <el-date-picker
                                :disabled="this.isSelected"
                                v-model="time"
                                style="width:90%;"
                                type="datetimerange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期">
                        </el-date-picker>
                    </div>
                    <div>
                        <p style="margin-top: 20px">空间范围：</p>
                        <el-input v-model="paramsFormData"
                                  style="width:90%;"
                                  :disabled="this.isSelected"
                                  clearable placeholder="请输入空间范围">
                        </el-input>
                        <span style="margin-left: 5px;">
                            <a @click="openPosition" id="icon">
                              <n3-icon type="map-marker" size="large"></n3-icon>
                            </a>
                        </span>
                    </div>
                    <el-button @click="load" type="primary" plain style="height:40px;width:35%;margin-top: 40px;">
                        加载
                    </el-button>
                    <el-button @click="submit" type="success" plain style="height:40px;width:35%;margin-left: 20px">
                        确定
                    </el-button>
                </el-col>
                <div v-show="isChart" id="chart" style="height: 400px;width: auto"></div>
                <div v-show="isTable" style="margin-top: 30px;height: 400px;width:60%">
                    <data-table :tableInData="tableData"></data-table>
                </div>
                <div class="chartIcon">
                    <i class="fa fa-pie-chart fa-2x" aria-hidden="true" @click="toPie"></i>
                    <i class="fa fa-bar-chart fa-2x" aria-hidden="true" @click="toBar"></i>
                    <i class="fa fa-line-chart fa-2x" aria-hidden="true" @click="toLine"></i>
                    <i class="fa fa-table fa-2x" aria-hidden="true" @click="toTable"></i>
                    <i class="fa fa-align-left fa-2x" aria-hidden="true" @click="toSbar"></i>
                    <i class="fa fa-undo fa-2x" aria-hidden="true" @click="toGauge"></i>
                </div>
            </div>
        </el-dialog>
        <div>
            <v_areaDialog :areaVisible="areaVisible"></v_areaDialog>
        </div>
    </div>
</template>

<script>
    import echarts from 'echarts';
    import areaDialog from '../../components/dialog/areaDialog';
    import dataTable from '../table/dataTable.vue'


    export default {
        name: "chartDivDialog",
        data() {
            return {
                tableData: null,
                // isTable:true,
                // isChart:false,
                isTable: false,
                isChart: true,
                isLoad: false,
                isSelected: false,
                time: '',
                paramsFormData: '',
                value: '',
                xfield: '',
                yfield: '',
                num: '',
                options: [],
                myOptions: [],
                PubOptions: [],
                fieldOption: [],
                fieldOptions: [],
                currentDiv: '',
                chartDataParams: {},
                chartType: 'bar',
                chartData: [],
                chartOptions: [],
                divOption: {},
                areaVisible: {
                    v: false
                },
            }
        },
        components: {
            "v_areaDialog": areaDialog,
            "data-table": dataTable
        },
        props: {
            chartDivDialogVisible: Object,
        },
        methods: {
            openPosition() {
                this.$Bus.$emit('areaVisible.v', true);
            },
            showTable() {
                let that = this;
                //我的数据
                this.$axios.get('/user/data?offset=0&size=100')
                    .then(function (res) {
                        let resultList = res.body.data;
                        let result = [];
                        for (let listData of resultList) {
                            if (listData.data.volume !== 0) {
                                result.push(listData);
                            }
                        }
                        let options = [];
                        for (let i = 0; i < result.length; i++) {
                            let option = {};
                            option.value = result[i].data.name;
                            option.label = result[i].data.name;
                            options.push(option);
                        }
                        that.myOptions = options;
                        // console.log(that.myOptions)
                        that.$axios.get('/data/list?offset=0&size=100')
                            .then(function (res) {
                                let resultList_1 = res.body.data;
                                let result_1 = [];
                                for (let listData of resultList_1) {
                                    if (listData.data !== null) {
                                        if (listData.data.volume !== 0) {
                                            result_1.push(listData);
                                        }
                                    }
                                }
                                let options_1 = [];
                                for (let i = 0; i < result_1.length; i++) {
                                    let option_1 = {};
                                    option_1.value = result_1[i].data.pk_meta_id;
                                    option_1.label = result_1[i].data.meta_name;
                                    options_1.push(option_1);
                                }
                                // console.log(options_1);
                                that.myOptions = that.myOptions.concat(options_1);
                                console.log(that.myOptions)
                                let newOption = [{value: '空气质量指数', label: '空气质量指数'}, {
                                    value: '平均PM2.5',
                                    label: '平均PM2.5'
                                }, {value: '气温', label: '气温'}, {value: '天气常见参数', label: '天气常见参数'}, {
                                    value: '污染大气观测指数',
                                    label: '污染大气观测指数'
                                },{value: '空气相对湿度', label: '空气相对湿度'},];
                                // console.log(that.myOptions)
                                that.myOptions = that.myOptions.concat(newOption);
                                console.log(that.myOptions)
                            }).catch(function (err) {
                            console.log(err);
                        });
                    }).catch(function (error) {
                    console.log(error)
                })
            },
            showField() {
                let that = this;
                if (this.value !== '') {
                    // if (this.value == '气温') {
                    //     that.isSelected = true;
                    //     that.fieldOption = [{xfield: "Time", xfieldName: "Time"}, {xfield: "Tem", xfieldName: "Tem"}];
                    //     that.fieldOptions = [{yfield: "Time", yfieldName: "Time"}, {yfield: "Tem", yfieldName: "Tem"}];
                    // } else if (this.value == '空气质量指数') {
                    //     that.fieldOption = [{xfield: "Time1", xfieldName: "Time"}, {xfield: "AQI", xfieldName: "AQI"}];
                    //     that.fieldOptions = [{yfield: "Time1", yfieldName: "Time"}, {yfield: "AQI", yfieldName: "AQI"}];
                    // } else if (this.value == '平均PM2.5') {
                    //     that.fieldOption = [{xfield: "Time2", xfieldName: "Time"}, {xfield: "PM", xfieldName: "PM"}];
                    //     that.fieldOptions = [{yfield: "Time2", yfieldName: "Time"}, {yfield: "PM", yfieldName: "PM"}];
                    //     console.log(that.fieldOption)
                    // } else if (this.value == '污染大气观测指数') {
                    //     that.fieldOption = [{xfield: "Kind", xfieldName: "Kind"}, {
                    //         xfield: "Value",
                    //         xfieldName: "Value"
                    //     }];
                    //     that.fieldOptions = [{yfield: "Kind", yfieldName: "Kind"}, {
                    //         yfield: "Value",
                    //         yfieldName: "Value"
                    //     }];
                    // } else if (this.value == '天气常见参数') {
                    //     that.fieldOption = [{xfield: "天气", xfieldName: "天气"}, {
                    //         xfield: "风向",
                    //         xfieldName: "风向"
                    //     }, {xfield: "气温", xfieldName: "气温"}];
                    //     that.fieldOptions = [{yfield: "天气", yfieldName: "天气"}, {
                    //         yfield: "风向",
                    //         yfieldName: "风向"
                    //     }, {yfield: "气温", yfieldName: "气温"}];
                    // } else {
                        this.$axios.get("/data//field/" + this.num)
                            .then(function (res) {
                                let result = res.body;
                                // console.log(result);
                                if (result.length == 0) {
                                    that.isSelected = true;
                                } else {
                                    let options = [];
                                    let optionse = [];
                                    for (let i = 0; i < result.length; i++) {
                                        let option = {};
                                        let opt = {};
                                        option.xfield = result[i].description;
                                        option.xfieldName = result[i].fieldName;
                                        opt.yfield = result[i].description;
                                        opt.yfieldName = result[i].fieldName;
                                        options.push(option);
                                        optionse.push(opt);
                                    }
                                    that.fieldOption = options;
                                    console.log(that.fieldOption);
                                    that.fieldOptions = optionse;
                                    console.log(that.fieldOptions);
                                }
                            }).catch(function (err) {
                            console.log(err);
                        })
                    // }
                }
            },
            changeDataFields(value) {
                this.num = value;
                this.isSelected = false;
                this.showField();
            },
            chartInit(val, chartData) {
                let option = {};
                if (val === 'bar') {
                    option = this.$changeChart.toBarchartData(chartData);
                } else if (val === 'line') {
                    option = this.$changeChart.toLinechartData(chartData);
                } else if (val === 'pie') {
                    option = this.$changeChart.toPiechartData(chartData);
                } else if (val === 'Sbar') {
                    option = this.$changeChart.toBarbarChartData(chartData);
                    console.log(option)
                }else if(val === 'gauge'){
                    option = this.$changeChart.toGuageChartData(chartData);
                }
                // }
                const chartDivDialog = echarts.init(document.getElementById('chart'));
                //清空画布
                chartDivDialog.clear();
                chartDivDialog.setOption(option);
                window.addEventListener('resize', function () {
                    chartDivDialog.resize()
                });
                this.divOption = option;
            },
            load() {
                let that = this;
                if (this.isSelected == true) {
                    if (this.value == '气温') {
                        this.chartData = [{"time": 2, "tem": 0}, {"time": 4, "tem": 1}, {
                            "time": 6,
                            "tem": 3
                        }, {"time": 8, "tem": 4}, {"time": 10, "tem": 5}, {"time": 12, "tem": 8}, {
                            "time": 14,
                            "tem": 14
                        }, {"time": 16, "tem": 12}, {
                            "time": 18, "tem": 8
                        }, {"time": 20, "tem": 5}, {"time": 22, "tem": 3}, {"time": 24, "tem": 1}];
                    }else if(this.value == '空气质量指数') {
                        this.chartData = [
                            {"Time": "1", "AQI": "93"},
                            {"Time": "2", "AQI": "89"},
                            {"Time": "3", "AQI": "85"},
                            {"Time": "4", "AQI": "79"},
                            {"Time": "5", "AQI": "79"},
                            {"Time": "6", "AQI": "75"},
                            {"Time": "7", "AQI": "72"},
                            {"Time": "8", "AQI": "71"},
                            {"Time": "9", "AQI": "60"},
                            {"Time": "10", "AQI": "60"},
                            {"Time": "11", "AQI": "55"},
                            {"Time": "12", "AQI": "53"},
                            {"Time": "13", "AQI": "53"},
                            {"Time": "14", "AQI": "59"},
                            {"Time": "15", "AQI": "62"},
                            {"Time": "16", "AQI": "65"},
                            {"Time": "17", "AQI": "68"},
                            {"Time": "18", "AQI": "79"},
                            {"Time": "19", "AQI": "85"},
                            {"Time": "20", "AQI": "95"},
                            {"Time": "21", "AQI": "95"},
                            {"Time": "22", "AQI": "102"},
                            {"Time": "23", "AQI": "104"},
                            {"Time": "24", "AQI": "100"}];
                    }else if(this.value == '平均PM2.5'){
                        this.chartData = [
                            {"Time":"1","pm":"230.1142857"},
                            {"Time":"2","pm":"229.1142857"},
                            {"Time":"3","pm":"221.8571429"},
                            {"Time":"4","pm":"216.2285714"},
                            {"Time":"5","pm":"215.9142857"},
                            {"Time":"6","pm":"220.8571429"},
                            {"Time":"7","pm":"214.0571429"},
                            {"Time":"8","pm":"200.9428571"},
                            {"Time":"9","pm":"198.1428571"},
                            {"Time":"10","pm":"206"},
                            {"Time":"11","pm":"218.5714286"},
                            {"Time":"12","pm":"229.9428571"},
                            {"Time":"13","pm":"246.1428571"},
                            {"Time":"14","pm":"247.4"},
                            {"Time":"15","pm":"254.2571429"},
                            {"Time":"16","pm":"255.1428571"},
                            {"Time":"17","pm":"251.2857143"},
                            {"Time":"18","pm":"253.9142857"},
                            {"Time":"19","pm":"263.1142857"},
                            {"Time":"20","pm":"259.6"},
                            {"Time":"21","pm":"268.2285714"},
                            {"Time":"22","pm":"266.4285714"},
                            {"Time":"23","pm":"265.3235294"},
                            {"Time":"24","pm":"262.6285714"}];
                    }else if(this.value == '污染大气观测指数'){
                        this.chartData = [
                            {"kind":"PM10","value":"100"},
                            {"kind":"PM2.5","value":"75"},
                            {"kind":"NO2","value":"23"},
                            {"kind":"SO2","value":"13"},
                            {"kind":"O3","value":"40"},
                            {"kind":"CO","value":"8"}];
                    }else if(this.value == '空气相对湿度'){
                        this.chartData = [{"sName":"空气湿度","description":"湿度","value":"35","unit":"%"}]
                    }else if(this.value == '天气常见参数'){
                        this.tableData = [
                                {"指标":"天气","状态":"晴"},
                                {"指标":"气温","状态":"0-14℃"},
                                {"指标":"风向","状态":"西北风"},
                                {"指标":"风速","状态":"<3级"},
                                {"指标":"湿度","状态":"24%"},
                                {"指标":"气压","状态":"1022hpa"}]
                    }else{
                        let queryUrl = "/parallel/result/preview/" + this.value + '?size=50000';
                        that.$axios.get(queryUrl).then(function (res) {
                            if (res.code == 200) {
                                console.log(res.body);
                                // that.chartInit(that.chartType, res.body);
                                that.chartData = res.body;
                                that.tableData = res.body;
                            } else {
                                that.$message(res.message);
                            }
                        })
                    }
                }
                else {
                    let statiData = {};
                    // statiData.tag=this.name;
                    statiData.dataId = this.value;
                    if (this.time != '') {
                        let start = this.time[0];
                        let end = this.time[1];
                        let star = new Date(start.toString().substring(4, 24));
                        let en = new Date(end.toString().substring(4, 24));
                        statiData.timeRange = star.getTime() + "," + en.getTime();
                    }
                    statiData.spatialFilter = this.paramsFormData;
                    // statiData.sql = this.inputAttr;
                    let xgroup = '';
                    for (let i = 0; i < this.fieldOption.length; i++) {
                        if (this.xfield == this.fieldOption[i].xfield) {
                            xgroup = this.fieldOption[i].xfieldName;
                        }
                    }
                    statiData.groupField = xgroup;
                    let ygroup = '';
                    for (let i = 0; i < this.fieldOptions.length; i++) {
                        if (this.yfield == this.fieldOptions[i].yfield) {
                            ygroup = this.fieldOptions[i].yfieldName;
                        }
                    }
                    statiData.statField = ygroup;
                    console.log(statiData);
                    let currentApplicationID = {};
                    this.$axios.post('/parallel/data/stat/' + statiData.dataId, statiData
                    ).then(function (response) {
                        // console.log(response);
                        currentApplicationID = response.body;
                        console.log(currentApplicationID);
                        that.$message({
                            type: 'success',
                            message: '任务提交成功，正在加载'
                        });
                    }).catch(function (error) {
                        that.$message({
                            type: 'warning',
                            message: '任务提交失败'
                        });
                    });
                    let superviseTimer = setInterval(function () {
                        that.$axios.get('/parallel/monitor/' + currentApplicationID)
                            .then(function (response) {
                                if (response.body.finalStatus == "UNDEFINED") {
                                    that.isLoad = true;
                                }
                                // if (response.body.finalStatus !== "SUCCEEDED") {
                                //     that.isLoad = true;
                                // }
                                else if (response.body.finalStatus === "FAILED"
                                    || response.body.finalStatus === "KILLED") {
                                    clearInterval(superviseTimer);
                                    that.isLoad = false;
                                    that.$message({
                                        type: 'warning',
                                        message: '加载失败'
                                    });
                                }
                                else {
                                    clearInterval(superviseTimer);
                                    that.isLoad = false;
                                    let queryUrl = "/parallel/result/preview/" + currentApplicationID + '?size=50000';
                                    that.$axios.get(queryUrl).then(function (res) {
                                        if (res.code == 200) {
                                            // that.chartInit(that.chartType, res.body);
                                            console.log(res);
                                            that.chartData = res.body;
                                            that.tableData = res.body;
                                        } else {
                                            that.$message(res.message);
                                        }
                                    })
                                }
                            })
                    }, 5000);
                }

            },
            submit() {
                if (this.isChart === true) {
                    this.chartDataParams.chartsData = this.divOption;
                    this.chartDataParams.currentId = this.currentDiv;
                    // this.chartDataParams.title = this.value + "图";
                    this.$Bus.$emit('chartDataParams', this.chartDataParams);
                    this.value = '';
                    const chartDivDialog = echarts.init(document.getElementById('chart'));
                    //清空画布
                    chartDivDialog.clear();
                }
                else if (this.isChart === false) {
                    this.chartDataParams.currentId = this.currentDiv;
                    this.chartDataParams.chartsData = this.tableData;
                    this.$Bus.$emit('chartDataParams', this.chartDataParams);
                    this.isTable =  false;
                    this.isChart = true;
                    this.value = '';
                    const chartDivDialog = echarts.init(document.getElementById('chart'));
                    //清空画布
                    chartDivDialog.clear();
                }
                this.chartDivDialogVisible.v = false;
            },
            toTable() {
                this.isChart = false;
                this.isTable = true;
            },
            toBar() {
                this.chartType = 'bar';
                this.isChart = true;
                this.isTable = false;
            },
            toPie() {
                this.chartType = 'pie';
                this.isChart = true;
                this.isTable = false;
            },
            toLine() {
                this.chartType = 'line';
                this.isChart = true;
                this.isTable = false;
            },
            toSbar() {
                this.chartType = 'Sbar';
                this.isChart = true;
                this.isTable = false;
            },
            toGauge() {
                this.chartType = 'gauge';
                this.isChart = true;
                this.isTable = false;
            }
        },
        created() {
            this.isLoad = false;
            let that = this;
            this.$Bus.$on('chartDivDialogVisible.v', (e) => {
                that.chartDivDialogVisible.v = e;
            });
            this.$Bus.$on('currentChartDiv', (e) => {
                this.currentDiv = e;
            });

        },
        mounted() {
            this.showTable();
            let that = this;
            this.$Bus.$on('coordinate', (params) => {
                // console.log(params);
                that.paramsFormData = params;
            });
        },
        watch: {
            chartType(newVal, oldVal) {
                console.log(newVal, oldVal);
                this.chartType = newVal;
                this.chartInit(newVal, this.chartData);
            },
            chartData(newValue, oldValue) {
                // this.chartData = newValue;
                this.chartInit(this.chartType, newValue);
            }
        },
    }
</script>

<style>
    .el-loading-mask {
        /*margin-top: 15vh;*/
        /*width: 64%;*/
        /*height: 600px;*/
        /*margin-left: 69vh*/
        z-index: 1000;
    }

    .chartIcon i {
        margin: 10px;
        /*border: 1px solid #ddd;*/
        padding: 6px 8px;
        font-size: 24px;
        text-align: left;
        color: #3a8ee6;
    }

    .chartIcon i:hover {
        color: #ddd;
    }

    .chartIcon {
        width: 50px;
        margin-top: 20px;
    }

    #chart {
        flex: 1;
    }

    .content {
        width: auto;
        display: flex;
    }
</style>